package com.jin.webvideo.externalInterfaces.youku;

import com.alibaba.fastjson.JSONObject;
import com.jin.webvideo.util.sys.ClientUtil;
import com.jin.webvideo.externalInterfaces.JSUtil;

import javax.script.ScriptException;
import java.io.IOException;

public class YoukuUtil {
    private static final String name = "YOUKUUTIL";
    private static final String SIGN = "getSign('%s', '%s')";
    static {
        // 预加载，只加载一次
        JSUtil.loadLocalJSFile("youkuSign.js", name);
    }
    public static JSONObject result(String sendData) throws IOException, ScriptException {
        JSONObject result = new JSONObject();
        String tk = ClientUtil.getCookie("youku.com","/", "_m_h5_tk");

        String url = (String) JSUtil.eval(String.format(SIGN, tk, sendData), name);
        String r = ClientUtil.httpGet(url);
        JSONObject obj = JSONObject.parseObject(r);
        // 可能是cookies失效，请求时重设cookie
        if (obj.getJSONObject("data").size() < 1 ){
            tk = ClientUtil.getCookie("youku.com","/", "_m_h5_tk");
            url = (String) JSUtil.eval(String.format(SIGN, tk, sendData), name);
            r = ClientUtil.httpGet(url);
        }
        obj = JSONObject.parseObject( r );
        result = obj.getJSONObject("data");
        return result;
    }

}
